package com.android.qjpmc.application_module.station.fragment;

import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RadioGroup;

import androidx.recyclerview.widget.LinearLayoutManager;

import com.android.qjpmc.R;
import com.android.qjpmc.application_module.contract.HisCurveDataContract;
import com.android.qjpmc.application_module.view.HisCurveLineChartView;
import com.android.qjpmc.application_module.viewModel.HisCurveDataViewModel;
import com.android.qjpmc.bean.GroupPointHisListBean;
import com.android.qjpmc.bean.PointParameterBean;
import com.android.qjpmc.bean.PwrDeviceBean;
import com.android.qjpmc.bean.StationDataBean;
import com.android.qjpmc.bean.StationDeviceBean;
import com.android.qjpmc.data_module.PwrDataModule;
import com.android.qjpmc.data_module.PwrDevice;
import com.android.qjpmc.data_module.PwrStation;
import com.android.qjpmc.data_module.PwrStationSet;
import com.android.qjpmc.databinding.FragmentStationHisCurveBinding;
import com.android.qjpmc.databinding.ItemHistoryDeviceValueItemBinding;
import com.android.qjpmc.databinding.SelectHistoryCurveBinding;
import com.android.qjpmc.widget.databindingadapter.BaseBindingItemPresenter;
import com.android.qjpmc.widget.databindingadapter.BaseDataBindingDecorator;
import com.android.qjpmc.widget.databindingadapter.SingleTypeBindingAdapter;
import com.android.qjpmc.widget.mvvm.factory.CreateViewModel;
import com.android.qjpmc.widget.mvvm.view.BaseMVVMFragment;
import com.android.qjpmc.widget.utils.DisplayUtils;
import com.android.qjpmc.widget.utils.TimeUtils;
import com.android.qjpmc.widget.utils.ToastUtils;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.orhanobut.logger.Logger;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@CreateViewModel(HisCurveDataViewModel.class)
public class HisCurveFragment extends BaseMVVMFragment<HisCurveDataViewModel, FragmentStationHisCurveBinding> implements BaseBindingItemPresenter<Object>, HisCurveDataContract.View {

    JCAnalogCurveSet m_curve_set = new JCAnalogCurveSet();
    PwrStation m_the_power_station = null;
    int m_SelectDeviceIndex = 0;
    int m_SelectValueIndex = 0;
    private SingleTypeBindingAdapter adapter;
    public int checkPointNumber;

    PwrStation GetThePwrStation() {
        return m_the_power_station;
    }

    void SetPwrStation(PwrStation station) {
        m_the_power_station = station;
    }


    @Override
    public int getLayoutId() {
        return R.layout.fragment_station_his_curve;
    }

    @Override
    public void initView() {
        IniDeviceList();
    }

    private StationDataBean stationData;
    private String stationId;

    public void initStationData(String stationId, StationDataBean data) {
        this.stationData = data;
        this.stationId = stationId;
    }

    @Override
    public void initData() {

    }

    String timeUnit = "";
    List<PointParameterBean> pointCodeList = new ArrayList<>();

    @Override
    public void initEvent() {
        mBinding.setView(this);
        mBinding.viewDevicesPoint.setDevicesPointListChooseListener(resultList -> {
            pointCodeList = new ArrayList<>();
            pointCodeList = resultList;

        });

        mBinding.rgTime.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == mBinding.rbTimeDay.getId()) {
                    timeUnit = "d";
                } else if (checkedId == mBinding.rbTimeHour.getId()) {
                    timeUnit = "h";
                } else if (checkedId == mBinding.rbTimeMinute.getId()) {
                    timeUnit = "m";
                } else if (checkedId == mBinding.rbTimeSecond.getId()) {
                    timeUnit = "s";
                } else {
                    timeUnit = "";
                }
            }
        });
        mBinding.llCheckSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (pointCodeList.size() <= 0) {
                    ToastUtils.showShort("请选择设备点");
                    return;
                }
                if (pointCodeList.size() > 3) {
                    ToastUtils.showShort("最多只能选择3条");
                    return;
                }
                if (TextUtils.isEmpty(m_start_time)) {
                    ToastUtils.showShort("请选择数据开始时间");
                    return;
                }
                if (TextUtils.isEmpty(m_end_time)) {
                    ToastUtils.showShort("请选择数据结束时间");
                    return;
                }

                long startTimeLong = TimeUtils.parsDataTimeLong(m_start_time, TimeUtils.DEFAULT_SDF);
                long endTimeLong = TimeUtils.parsDataTimeLong(m_end_time, TimeUtils.DEFAULT_SDF);
                if (startTimeLong >= endTimeLong) {
                    ToastUtils.showShort("开始时间不能大于结束时间");
                    return;
                }
                if (TextUtils.isEmpty(timeUnit)) {
                    ToastUtils.showShort("请选择数据时间间隔类型");
                    return;
                }
                String intervalValue = mBinding.etTimeValue.getText().toString().trim();
                if (TextUtils.isEmpty(intervalValue)) {
                    ToastUtils.showShort(mBinding.etTimeValue.getHint());
                    return;
                }

                Map<String, Object> commonMap = new HashMap();
                commonMap.put("stime", m_start_time);
                commonMap.put("etime", m_end_time);
                commonMap.put("interval", intervalValue);
                commonMap.put("timeUnit", timeUnit);
                commonMap.put("func", "first");
                Map<String, List<PointParameterBean>> queryPointMap = new HashMap<>();
                //组装请求数据
                for (PointParameterBean pointParameterBean : pointCodeList) {
                    String deviceTypeCode = pointParameterBean.deviceTypeCode;
                    if (queryPointMap.containsKey(deviceTypeCode)) {
                        List<PointParameterBean> list = queryPointMap.get(deviceTypeCode);
                        list.add(pointParameterBean);
                    } else {
                        List<PointParameterBean> list = new ArrayList<>();
                        list.add(pointParameterBean);
                        queryPointMap.put(deviceTypeCode, list);

                    }
                }
                //构建请求相关参数
                for (String key : queryPointMap.keySet()) {
                    List<PointParameterBean> pointParameterList = queryPointMap.get(key);
                    Map<String, Object> paramsMap = new HashMap<>();
                    Map<String, PointParameterBean> propsDataMap = new HashMap<>();
                    paramsMap.putAll(commonMap);
                    paramsMap.put("stbName", key);
                    List<String> colNameList = new ArrayList<>();
                    List<String> deviceCodeList = new ArrayList<>();
                    for (PointParameterBean pointParameterBean : pointParameterList) {
                        colNameList.add(pointParameterBean.propsCode);
                        //将每一个点的数据存下来,可以通过propsCode获取 用于构建每一个图表的title 详见returnGroupPointDataList的title组成
                        propsDataMap.put(pointParameterBean.propsCode, pointParameterBean);
                        deviceCodeList.add(pointParameterBean.deviceCode);
                    }
                    paramsMap.put("colNameList", colNameList);
                    paramsMap.put("deviceCodeList", deviceCodeList);
                    Logger.d(paramsMap);
                    mViewModel.getPointDataOfStation(stationData, paramsMap, propsDataMap);

                }
            }
        });

    }

    @Override
    public void onItemClick(int position, Object itemData) {

    }

    ArrayList<ILineDataSet> dataSets = new ArrayList<ILineDataSet>();

    @Override
    public void returnGroupPointDataList(List<GroupPointHisListBean> pointDataList) {
        //   ToastUtils.showShort("数据获取到了 要刷新了");
        Logger.d("pointDataList" + pointDataList.toString());
        mBinding.llChartLayout.removeAllViews();
        if (pointDataList.size() > 0) {
            for (GroupPointHisListBean groupPointHisListBean : pointDataList) {
                HisCurveLineChartView chartView = new HisCurveLineChartView(mActivity);
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, (int) DisplayUtils.getDimension(R.dimen.dp_300));
                params.topMargin = (int) DisplayUtils.getDimension(R.dimen.dp_10);
                chartView.setLayoutParams(params);
                String title = stationData.companyName + groupPointHisListBean.deviceName + groupPointHisListBean.propsName;
                chartView.initializeChart(title, groupPointHisListBean.pointValueList);
                mBinding.llChartLayout.addView(chartView);
            }
        }else {
            ToastUtils.showShort("没有数据");
        }

    }


    void IniDeviceList() {

        List<StationDeviceBean> device_bean_list = new ArrayList<>();
        PwrStationSet set = PwrDataModule.getInstance().GetPwrStationSet();
        StationDeviceBean theBean = null;
        PwrStation ThePwrStation = PwrDataModule.getInstance().GetCurrentStationNode();
        SetPwrStation(ThePwrStation);
        if (ThePwrStation != null) {
            PwrDevice TheDevice = ThePwrStation.GetFirstDevice();
            while (TheDevice != null) {
                theBean = new StationDeviceBean();//
                theBean.m_ThePwrDevice = TheDevice;
                TheDevice = TheDevice.GetNext();
                device_bean_list.add(theBean);
            }
        }
        mBinding.viewDevicesPoint.initDevicesListData(stationData.stationGroupList);

      /*  mBinding.recyclerView.setLayoutManager(new LinearLayoutManager(this.getContext()));
        adapter = new SingleTypeBindingAdapter(this.getContext(), stationData.stationGroupList, R.layout.select_history_curve);
        adapter.setItemPresenter(this);
        mBinding.recyclerView.setAdapter(adapter);
        adapter.setItemDecorator((BaseDataBindingDecorator<PwrDeviceBean, SelectHistoryCurveBinding>) (binding, position, viewType, data) -> {
            // 不可嵌套滑动
            binding.itemRecyclerView.setNestedScrollingEnabled(false);
            // 取消head 的 recycleView的焦点
            binding.itemRecyclerView.setFocusableInTouchMode(false);
            //设置布局管理器
            binding.itemRecyclerView.setLayoutManager(new LinearLayoutManager(this.getContext()));

            *//*ArrayList<DeviceValueBean> ValueList = new ArrayList<DeviceValueBean>();
            StationDeviceBean TheDevice = device_bean_list.get(position);

            DeviceValueBean value_bean = null;
            if (TheDevice != null) {
                ArrayList<AnalogDataItem> AnalogList = TheDevice.m_ThePwrDevice.GetAnalogDataList();
                if (AnalogList != null) {
                    for (AnalogDataItem item : AnalogList) {
                        value_bean = new DeviceValueBean();
                        if (value_bean != null) {
                            value_bean.m_DataItem = item;
                            ValueList.add(value_bean);
                        }
                    }
                }
                ;
            }
*//*

            SingleTypeBindingAdapter itemAdapter = new SingleTypeBindingAdapter(this.getContext(), data.pointList, R.layout.item_history_device_value_item);
            binding.itemRecyclerView.setAdapter(itemAdapter);
            binding.itemRecyclerView.setVisibility(data.isOpen ? View.VISIBLE : View.GONE);
            binding.ivOpen.setRotation(data.isOpen ? 180 : 0);
//            if (data.m_ThePwrDevice != null) {
//                binding.tvName.setText(data.m_ThePwrDevice.getM_Name());
//            }
            binding.tvName.setText(data.deviceName);

            // binding.
            itemAdapter.setItemDecorator((BaseDataBindingDecorator<PointParameterBean, ItemHistoryDeviceValueItemBinding>) (binding2, position2, viewType2, the_value) -> {

               *//* if (the_value.m_DataItem != null) {
                    binding2.tvName.setText(the_value.m_DataItem.m_Name);
                }*//*
                binding2.tvName.setText(the_value.propsName);
               *//* PwrStation station = GetThePwrStation();
                if (station != null) {
                    AnalogDataItem value_item = station.GetAnalogDataItem(position, position2);

                    if (value_item != null) {
                        if (m_curve_set.IsCurveExist(value_item) != null) {
                            binding2.checkBox.setChecked(true);
                        } else {
                            binding2.checkBox.setChecked(false);
                        }
                    } else {
                        binding2.checkBox.setChecked(false);
                    }
                    //for (AnalogDataItem item: AnalogList)


                } else {
                    binding2.checkBox.setChecked(false);
                }*//*
                binding2.checkBox.setSelected(the_value.isCheck);
                binding2.llContent.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (!the_value.isCheck) {
                            if (checkPointNumber > 2) {
                                ToastUtils.showShort("最多选择3条");
                                the_value.isCheck = false;
                            } else {
                                the_value.isCheck = true;
                                checkPointNumber++;
                            }
                        } else {
                            the_value.isCheck = false;

                            checkPointNumber--;
                        }
                        binding2.checkBox.setSelected(the_value.isCheck);
                    }
                });
*//*
                binding2.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                        the_value.isCheck = isChecked;

                        if (isChecked) {
                            if (checkPointNumber >= 2) {
                                ToastUtils.showShort("最多选择3条");
                            } else {
                                checkPointNumber++;
                            }
                        } else {
                            checkPointNumber--;
                        }

                            *//*
         *//*m_SelectDeviceIndex = position;
                            m_SelectValueIndex = position2;
                            PwrStation station = GetThePwrStation();
                            if (station != null) {
                                AnalogDataItem value_item = station.GetAnalogDataItem(m_SelectDeviceIndex, m_SelectValueIndex);

                                if (isChecked == true) {
                                    if (m_curve_set.GetCurveCount() >= 6) {
                                        return;
                                    }
                                    m_curve_set.AddCurve(value_item, Color.RED);
                                } else {
                                    m_curve_set.RemoveCurve(value_item);
                                }
                                LineData this_data = new LineData(m_curve_set.CreateDataSets());
                                mBinding.chart.setData(this_data);
                            }*//**//*

                    }
                });
*//*

            });


        });*/
    }

    String m_start_time;
    String m_end_time;

    public void onCheckDevices(int position, PwrDeviceBean itemData) {
        itemData.isOpen = !itemData.isOpen;
        itemData.itemPosition = position;
        Logger.d("onCheckDevices" + (itemData.pointList == null));
        if (itemData.pointList == null) {
            mViewModel.getPointListOfGroup(itemData);
        } else {
            returnGroupPointList(itemData);
        }
    }

    @Override
    public void returnGroupPointList(PwrDeviceBean data) {
        adapter.notifyItemChanged(data.itemPosition);
    }


    TimePickerView pvStartTime;
    TimePickerView pvEndTime;

    public void onSelectStartTime() {
        if (pvStartTime == null) {

            Calendar minDate = Calendar.getInstance();
            minDate.set(Calendar.YEAR, 1990);
            minDate.set(Calendar.MONTH, Calendar.JANUARY);
            minDate.set(Calendar.DAY_OF_MONTH, 1);
            Calendar maxDate = Calendar.getInstance();
            maxDate.setTimeInMillis(System.currentTimeMillis());

            pvStartTime = new TimePickerBuilder(this.getContext(), new OnTimeSelectListener() {
                @Override
                public void onTimeSelect(Date date, View v) {
                    m_start_time = TimeUtils.DEFAULT_SDF.format(date);
                    mBinding.tvStartTime.setText(m_start_time);
                }
            }).setRangDate(minDate, maxDate).setDate(maxDate).setType(new boolean[]{true, true, true, true, true, true})
                    .build();
        }

        pvStartTime.show();
    }

    public void onSelectEndTime() {
        if (pvEndTime == null) {
            Calendar minDate = Calendar.getInstance();
            minDate.set(Calendar.YEAR, 1990);
            minDate.set(Calendar.MONTH, Calendar.JANUARY);
            minDate.set(Calendar.DAY_OF_MONTH, 1);
            Calendar maxDate = Calendar.getInstance();
            maxDate.setTimeInMillis(System.currentTimeMillis());
            pvEndTime = new TimePickerBuilder(this.getContext(), new OnTimeSelectListener() {
                @Override
                public void onTimeSelect(Date date, View v) {
                    m_end_time = TimeUtils.DEFAULT_SDF.format(date);
                    mBinding.tvEndTime.setText(m_end_time);
                }
            }).setRangDate(minDate, maxDate).setDate(maxDate)
                    .setType(new boolean[]{true, true, true, true, true, true})
                    .build();
        }
        pvEndTime.show();
    }
}

